# -*- coding:utf-8 -*-
# @desc Flask Web应用
# @ref Flask文档 https://www.bookstack.cn/read/Flask-2.0-zh/43e89ae1d470035d.md
import os.path
import re
import time
from time import sleep

from flask import Flask, render_template, request, jsonify
import requests
import subprocess
from bs4 import BeautifulSoup
import uiautomator2 as u2

# 参数 路由 模板
from common import success, fail
from utils.login import login, logout

Sessions = []
SessionsV2 = {}


def get_id(id) -> str:
    return 'com.a169kai.tiansui:id/' + id



app = Flask(__name__, static_folder='app', static_url_path='/app', template_folder='app')
APP_PACKAGE = 'com.a169kai.tiansui'
UI = 'uiautomator2'


@app.route('/screen')
def screen():
    ip = request.args.get('ip').strip()

    p = subprocess.Popen(f'scrcpy -s {ip}', stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)
    output, error = p.communicate()
    p.wait()
    if error:
        return fail(msg=f'命令执行失败 {error.decode("utf-8")}')
    return success(msg='投屏成功')


@app.route('/push')
def app_file_push():
    return 'push a file to devices'


@app.route('/install')
def download_file():
    # url = 'https://www.tiansuixiansheng.com/suan2/new.apk'

    url = '//192.168.0.230/share/多渠道android包目录/20220704_2.1.12/huawei/release/ts-app-V2.1.12-202207042123.apk'
    _ui_action('app_install', url)

    return success(msg='下载成功')


@app.route('/ui.logout')
def app_logout():
    key = request.args.get('key')
    d = _session_store(key)

    d(text="我的").click(timeout=1.5)
    d(resourceId='com.a169kai.tiansui:id/ll_setting').click(timeout=0.5)
    d(resourceId='com.a169kai.tiansui:id/btn_login_out').click(timeout=0.5)
    d(resourceId='com.a169kai.tiansui:id/btn_selectPositive').click(timeout=0.5)
    # for d in Sessions:
    #     try:
    #         logout(d)
    #     except Exception as e:
    #         print(e)

    return success(msg='执行成功')


def _session_store(key) -> u2.Device:
    global SessionsV2

    if key in SessionsV2:
        d = SessionsV2[key]
    else:
        d = u2.connect(key)
        SessionsV2[key] = d

    return d


@app.route('/ui.book')
def add_book():
    key = request.args.get('key')
    d = _session_store(key)
    # 首页
    d(resourceId=get_id('navigation_home')).click()
    # 点击命书icon
    d(resourceId=get_id('iv_book')).click()
    # 新增命书
    d(resourceId=get_id('tv_insert_book')).click()
    # 昵称
    d(resourceId=get_id('et_nikeName')).set_text('测试A')
    # 点击性别
    d(resourceId=get_id('ll_gender')).click()
    # 选男的
    d(resourceId=get_id('iv_man')).click()
    # 点击生日
    d(resourceId=get_id('ll_birthday')).click()
    # 确认选择生日
    d(resourceId=get_id('btn_submit')).click()
    # 提交按钮
    d(resourceId=get_id('ll_open_book')).click()
    # 全部解锁
    d(resourceId=get_id('btn_unloc_know')).click()
    # 确定
    d(resourceId=get_id('btn_selectPositive')).click()

    return success(msg='执行成功')


@app.route('/ui.check_book')  # 我的命书
def check_book():
    key = request.args.get('key')
    d = _session_store(key)

    d(resourceId=get_id('navigation_home')).click()
    # 点击命书icon
    d(resourceId=get_id('iv_book')).click()
    # 立即开启命书
    d(resourceId=get_id('ll_open_book')).click()

    tabs = {
        'iv_bz': ['八字分析', '格局分析', '命局分析', '四柱分析', '性格分析', '论十二宫', '五行建议'],
        'iv_zs': ['论财运', '论事业', '论情感', '论健康'],
        'iv_ys': ['论大运', '论流年'],
    }
    for k, val in tabs.items():
        d(resourceId=get_id(k)).click()
        for txt in val:
            d(resourceId=get_id('tv_tab'), text=txt).click()
        sleep(0.5)


@app.route('/ui.month_luck')  # 月运势
def month_luck():
    key = request.args.get('key')
    d = _session_store(key)
    d(resourceId=get_id('tv_tab_title')).click()

    tabs = {
        'tv_lunar': ['农历冬月', '农历腊月', '农历正月', '农历二月', '农历三月', '农历四月', '农历五月', '农历六月', '农历七月', '农历八月', '农历九月', '农历十月',
                     '农历冬月', '农历腊月', '农历正月'],
    }
    for k, val in tabs.items():
        d(resourceId=get_id(k)).click()
        for txt in val:
            d(resourceId=get_id('tv_lunar'), text=txt).click()
        sleep(0.5)


@app.route('/ui.check_article')  # 查看文章
def check_artile():
    key = request.args.get('key')
    d = _session_store(key)

    # 点击探索icon
    d(resourceId=get_id('iv_explore')).click()

    tabs = {
        'tv_tab_title': ['推荐', '国学文化', '哲学命理', '命理运势', '姻缘情感', '明星八字', '智慧人生', '国学典故', '奇闻轶事'],
    }

    for k, val in tabs.items():
        d(resourceId=get_id(k)).click()
        for txt in val:
            d(resourceId=get_id('tv_tab_title'), text=txt).click()
        sleep(0.5)


@app.route('/ui.details')  # 文章详情
def ts_details():
    key = request.args.get('key')
    d = _session_store(key)

    d(resourceId=get_id('tv_tab_title')).click()
    # 进入文章页
    d(resourceId=get_id('iv_pic')).click()

    time.sleep(2)
    # 点赞
    d(resourceId=get_id('like_icon_bottom')).click()


@app.route('/ui.measure')  # 解惑板块
def jiehuo_measure():
    key = request.args.get('key')
    d = _session_store(key)

    d(resourceId=get_id('smallLabel')).click()

    tabs = {
        'id/tv_title': ['生肖配对', '生男生女', '神机妙算', '眼皮跳测吉凶'],
    }
    for k, val in tabs.items():
        d(resourceId=get_id(k)).click()
        for txt in val:
            d(resourceId=get_id('id/tv_title'), text=txt).click()
        sleep(0.5)


@app.route('/ui.login')  # 登录注册
def app_login():
    key = request.args.get('key')
    d = _session_store(key)
    # 同意协议
    d(resourceId=get_id('iv_rb')).click(timeout=1.5)
    # 手机登录、注册
    d(resourceId=get_id('login_mobile')).click()

    # 输入手机
    d(resourceId=get_id('et_mobile')).set_text('18693995509')
    # # 输入验证码
    d(resourceId=get_id('et_sms')).set_text(666888)
    # 同意协议
    d(resourceId=get_id('iv_rb')).click()
    # 登录
    d(resourceId=get_id('login_submit')).click()
    d.wait_activity('.ImproveDataActivity', timeout=1.5)
    print(d.app_current().get('activity'))
    # 如果新用户，填入昵称等信息然后继续进入首页
    if '.ImproveDataActivity' in d.app_current().get('activity'):
        # 输入昵称
        d(resourceId=get_id('et_nikeName')).set_text('mini')
        d(resourceId=get_id('btn_next')).click()
        # 选择男
        d(resourceId=get_id('ll_man')).click()
        d(resourceId=get_id('btn_next')).click()
        # 跳过地区
        d(resourceId=get_id('btn_next')).click()
        # 选择时间
        d(resourceId=get_id('tv_birthday')).click()
        # 确认时间
        d(resourceId=get_id('btn_submit')).click()
        # 点击弹窗确认
        d(resourceId=get_id('tv_sure')).click()

    # d(resourceId=get_id('et_nikeName'))
    # check_if_new_blood()
    # 关闭开屏弹窗
    d(resourceId=get_id('iv_cancel')).click()
    # 点击同意协议
    # d(className='android.widget.CheckBox').click_exists(timeout=1)

    # 点击登录
    # d(resourceId='login_btn').click()

    return success(msg='执行成功')


@app.route('/disconnect')
def disconnect():
    ip = request.args.get('ip').strip()
    p = subprocess.Popen(f'adb disconnect {ip}', stdout=subprocess.PIPE, shell=True, stderr=subprocess.PIPE)
    output, error = p.communicate()
    p.wait()
    if error:
        return fail(msg=f'执行失败！ {error}')
    return success(msg='成功断开')


@app.route("/connect")
def connect():
    serial = request.args.get('k').strip()

    ip_info = subprocess.Popen(f'adb -s {serial} shell ip address', stdout=subprocess.PIPE, shell=True)
    ip_info = ip_info.stdout.read().decode()
    r = re.compile('192\.168\.0\.\d+')
    result = r.search(ip_info)
    if result is None:
        return fail(msg='设备IP不在搜索范围！')
    ip = result.group()
    try:
        subprocess.Popen(f'adb -s {serial} tcpip 5555', stdout=subprocess.PIPE, shell=True).wait(1)
        subprocess.Popen(f'adb connect {ip}:5555', stdout=subprocess.PIPE, shell=True).wait(1)
    except subprocess.TimeoutExpired as e:

        return fail(msg='连接设备发生错误！')
    return success(msg=f'你的设备{serial}输入的IP是 {ip}')


@app.route('/start')
def app_start():
    _ui_action('app_start', APP_PACKAGE)

    return success(msg='一键打开成功')


@app.route('/stop')
def app_stop():
    _ui_action('app_stop', APP_PACKAGE)

    return success(msg='一键停止成功')


@app.route('/uninstall')
def app_uninstall() -> str:
    _ui_action('app_uninstall', APP_PACKAGE)
    return success(msg='一键卸载成功')


def _ui_action(action: u2.Device.__getattribute__, *args):
    global Sessions
    if len(Sessions) > 0:
        for session in Sessions:
            session.__getattribute__(action)(*args)

    else:
        ip_pool = get_ips(only_ips=True)
        Sessions.clear()
        for ip in ip_pool:
            d = u2.connect(ip)
            Sessions.append(d)
            d.__getattribute__(action)(*args)


@app.route('/spider')
def spider():
    """简单爬虫"""
    url = request.args.get('url')
    r = requests.get(url)

    with open('app/spider.html', 'wb') as f:
        f.write(r.content)
        f.close()

    bs = BeautifulSoup(open('app/spider.html', encoding='utf-8'), 'lxml', from_encoding='utf8')
    # 写法需要探索

    return r.content


@app.route('/')
def home():
    info, ip_pool = get_ips()

    # if not len(Sessions):
    #     for ip in ip_pool:
    #         Sessions.append(u2.connect(ip))

    return render_template('home.html', info=info)


def get_ips(only_ips=False):
    devices = subprocess.Popen('adb devices -l', stdout=subprocess.PIPE, shell=True)
    devices.wait()
    info = devices.stdout.read()
    info = info.decode()
    searched = re.compile('192\.168\.0\.\d+', re.M)
    if only_ips:
        return searched.findall(info)

    return info, searched.findall(info)


if __name__ == '__main__':
    app.env = 'development'
    app.run(debug=True, host='0.0.0.0')
